//
//  UIImageView+Additions.m
//  TouchableImageView
//
//  Created by Johnny on 4/25/14.
//  Copyright (c) 2014 Johnny. All rights reserved.
//

#import "UIImageView+Additions.h"
#import "UIImageView+Webcache.h"

@implementation UIImageView (Additions)

- (void)setImageWithURL:(NSURL *)url imageType:(UIImageViewThumbType)imageType
{
    [self setImageWithURL:url placeholderImage:nil imageType:imageType];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage imageType:(UIImageViewThumbType)imageType
{
    NSString *urlString = url.absoluteString;
    NSString *suffix = [self suffixWithImageType:imageType];
    if (suffix && [urlString hasSuffix:suffix] == NO) {
        urlString = [urlString stringByAppendingString:suffix];
    }
    
    [self sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:placeholderImage];
}

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
{
    self.userInteractionEnabled = YES;
    UIControl *touchControl = [[UIControl alloc] initWithFrame:self.bounds];
    touchControl.tag = self.tag;
    [self addSubview:touchControl];
    
    [touchControl addTarget:target action:action forControlEvents:controlEvents];
}

#pragma mark - Private

- (NSString *)suffixWithImageType:(UIImageViewThumbType)imageType
{
    NSString *suffix = nil;
    
    switch (imageType) {
        case UIImageViewThumbTypeSmall:
            suffix = @"!200x200";
            break;
            
        case UIImageViewThumbTypeMiddle:
            suffix = @"!400x400";
            break;
            
        case UIImageViewThumbTypeLarge:
        case UIImageViewThumbTypeOriginal:
            break;
            
        default:
            break;
    }
    
    return suffix;
}

@end
